package com.city.project.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class LoginCheckFilter
 */
@WebFilter("/*")
public class LoginCheckFilter implements Filter {

    /**
     * Default constructor.
     */
    public LoginCheckFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        System.out.println("开始登陆过滤");
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;

        String uri = req.getRequestURI();
        if (uri.endsWith(".svg") || uri.endsWith(".js") || uri.endsWith(".css") || uri.endsWith(".png")
            || uri.endsWith(".jpg") || uri.endsWith(".eot") || uri.endsWith(".ttf") || uri.endsWith(".woff")
            || uri.endsWith(".woff2") || uri.endsWith("preview.html")) {
            chain.doFilter(request, response);
        } else {
            String appName = req.getServletContext().getContextPath();
            System.out.println("=======================" + appName);
            if (uri.equals(appName + "/login/login.jsp") || uri.equals(appName + "/login/login.do")
                || uri.equals(appName + "/hint/LoginManagersError.jsp") || uri.equals(appName + "/hint/iperror.jsp")) {
                // 允许通过拦截器方法
                chain.doFilter(request, response);
            } else {
                HttpSession session = req.getSession();
                String username = (String)session.getAttribute("username");

                if (username == null) {
                    res.sendRedirect(appName + "/login/login.jsp");
                } else {
                    // 允许通过拦截器方法
                    chain.doFilter(request, response);
                }
            }
        }

    }

    /**
     * @see Filter#init(FilterConfig)
     */
    @Override
    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}
